<template>
  <el-select
    class="user-search event-user-search"
    :value="value"
    @input="choose"
    filterable
    remote
    :placeholder="field.placeHolder ? field.placeHolder : $t('common.base.inputKeywordToSearch')"
    :clearable="field.clearable ? field.clearable : false"
    :loading="loading"
    :remote-method="searchLinkman"
    :popper-append-to-body="false"
    v-el-select-loadmore={loadmoreOptions}
  >
    <el-option
      v-for="(item, index) in options"
      :key="`${item.id}_${index}`"
      :label="item.name"
      :value="field.returnData ? item[field.returnData] : item.id"
    >
      <div class='linkman-search-option'>
        <span>{{ item.name || '' }}</span>
        <span>{{ item.phone || '' }}</span>
      </div>
    </el-option>
  </el-select>
</template>

<script>
/* api */
import { getTaskCustomerLinkman } from '@src/api/TaskApi.ts'
/* mixin */
import FormMixin from '@src/component/form/mixin/form'
/* model */
import Page from '@model/Page'
/* util */
import _ from 'lodash'
import Log from '@src/util/log.ts'
import { debounce } from '@src/util/function'
import { isOpenData } from '@src/util/platform'
export default {
  name: 'linkman-search',
  mixins: [FormMixin],
  props: {
    value: {
      type: String,
      default: '',
    },
    userList: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    /* 判断是否自定义视图进来的 */
    userList(v) {
      if (Array.isArray(v) && v.length) {
        this.options = v;
      }
    },
  },
  data() {
    return {
      isOpenData,
      loading: false,
      options: [],
      loadmoreOptions: {
        disabled: false,
        callback: this.loadmore,
        distance: 10,
      },
      page: new Page()
    };
  },
  created() {
    let options = sessionStorage.getItem(`${this.field.fieldName}_options`);

    if (Array.isArray(this.userList) && this.userList.length) {
      this.options = this.userList;
    } else {
      if(!this.isOpenData) {
        this.options = JSON.parse(options || '[]');
      }
    }
  },
  methods: {
    choose(newValue) {
      let oldValue = null;
      this.$emit("update", { newValue, oldValue, field: this.field, options: this.options });
    },
    async fetchRemoteData(keyword) {
      // 参数
      const params = { keyword, pageNum: this.page.pageNum }

      try {
        const data = await getTaskCustomerLinkman(params)
        const result = data?.result || {}

        this.loadmoreOptions.disabled = Boolean(!result?.hasNextPage)
        return result

      } catch (error) {
        Log.error(error, this.fetchRemoteData.name)
        return {}
      } finally {
        this.loading = false
      }

    },
    async loadmore() {
      if (this.loading || this.loadmoreOptions.disabled) return

      this.loadmoreOptions.disabled = true
      this.loading = true
      this.page.pageNum += 1

      try {
        const result = await this.fetchRemoteData()
        const userList = result?.list

        this.page.merge(result)
        this.setOptions(userList)

      } catch (error) {
        Log.error(error, this.loadmore.name)
      }

    },
    setOptions(linkmans = []) {
      const options = linkmans.slice()

      this.options = this.options.concat(
        options.map(({ displayName, userId, name, id, phone = '' }) => {
          return (
            Object.freeze({
              name: displayName || name || '',
              id: userId || id || '',
              phone
            })
          )
        })
      )

      this.setSessionStorageOptions()
    },
    setSessionStorageOptions() {
      sessionStorage.setItem(
        `${this.field.fieldName}_options`,
        JSON.stringify(this.options)
      )
    },
    searchLinkman(keyword) {
      debounce(async () => {
        if (this.loading) return

        this.loading = true
        this.page = new Page()
        this.options = []
        this.$emit('input', { keyword, field: this.field })

        try {
          const result = await this.fetchRemoteData(keyword)
          const userList = result?.list

          this.page.merge(result)
          this.setOptions(userList)

        } catch (error) {
          Log.error(error, this.loadmore.name)
        }
      })
    }
  },
};
</script>

<style lang="scss">
.user-search {
  width: 100%;
}
.event-user-search {
  .el-select-dropdown__item {
    height: 100%;
    line-height: normal;
    padding: 8px;
  }
}
.linkman-search-option {
  width: 100%;
  display: flex;
  justify-content: space-between;
  word-wrap: break-word;
  white-space: normal;
  span {
    word-wrap: break-word;
    white-space: normal;
  }
}
</style>
